package com.blank.white.bussiness;


import com.blank.black.entity.pojo.BlankConfig;
import com.blank.black.service.IBlankConfigService;
import com.blank.white.common.enums.CachePreEnum;
import com.blank.white.common.util.CacheUtil;
import com.blank.white.entity.req.ListReq;
import com.blank.white.entity.req.TableInfoReq;
import com.blank.white.entity.vo.TableInfoVO;
import com.blank.white.service.IConfigService;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.blank.white.common.exception.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Description: 配置业务类
 */
@Component
public class ConfigBusService {

    @Resource
    IBlankConfigService blankConfigService;

    @Resource
    IConfigService configService;
    @Qualifier("CACHE_DEFAULT")
    @Resource
    private LoadingCache<String, Object> loadingCache;


    public BlankConfig getBlankConfigById(Long id)  {
        try {
            return blankConfigService.selectById(id);
        } catch (Exception e) {
            throw new BusinessException(ErrorsEnum.EXCEPTION_CONFIG_ERROR,e.getMessage());
        }
    }

    public PageInfo<BlankConfig> list(ListReq listReq) {
        return configService.listTopBlankConfig(listReq);
    }

    public Integer deleteBlankConfigById(Long id) {
        if(!CacheUtil.lockByConfigId(id,loadingCache)) {
            throw new BusinessException(ErrorsEnum.EXCEPTION_CONFIG_LOCK_ERROR);
        }
        Integer res = configService.deleteExampleConfigById(id);
        loadingCache.invalidate(CachePreEnum.CONFIG_ID_LOCK.getName()+id);
        return res;
    }

    public PageInfo<TableInfoVO> listTable(TableInfoReq req) {
        return configService.listTable(req);
    }

    public PageInfo<String> listTableSchema(TableInfoReq req) {
        return configService.listTableSchema(req);
    }


    public Long editBlankConfig(BlankConfig blankConfig) {
        Long topId = 0L;
        if (Objects.isNull(blankConfig)) {
            throw new BusinessException(ErrorsEnum.PARAM_ERROR,"配置参数为空");
        }
        if (Objects.nonNull(blankConfig.getId()) && blankConfig.getId() > 0) {
            if(!CacheUtil.lockByConfigId(blankConfig.getId(),loadingCache)) {
                throw new BusinessException(ErrorsEnum.EXCEPTION_CONFIG_LOCK_ERROR);
            }
            topId = configService.updateBlankConfig(blankConfig);
            loadingCache.invalidate(CachePreEnum.CONFIG_ID_LOCK.getName()+blankConfig.getId());
        } else {
            topId = configService.insertBlankConfig(0L,blankConfig);
        }

        return topId;
    }
}
